package Test.restful;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.general.BaseBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-05-17
 * @Description: Restful接口测试
 * @ModifyLog:
 **/

public class RestfulTestUtil {
    /**
    *@Description: 发送post请求
    *@Param: [url, param]
    *@return: java.lang.String
    *@Author: Dusongsong
    *@Date: 2020/11/17
    */
    public static String sendPostHttpRequest(String url,JSONObject param){
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try{
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //1.获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            //2.中文有乱码的需要将PrintWriter改为如下
            //out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
    *@Description: 发送请求
    *@Param: [url]
    *@return: json
    *@Author: Dusongsong
    *@Date: 2020/11/17
    */
    public static JSONObject httpGet(String url) {
        BaseBean baseBean = new BaseBean();

        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(6000).setConnectTimeout(6000).build();
        request.setConfig(requestConfig);
        request.setHeader("Authorization","80fb6d32-fe56-43f2-9a2e-bf5ec6b6a2d6");//token值
        try {
            CloseableHttpResponse response = client.execute(request);
            //请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                //把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                System.out.println("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            System.out.println("get请求提交失败:");
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 生成http请求头Authorization串，用于鉴权
     */
    private static String generateAuthorization(String username, String password) {
        String md5Pwd = DigestUtils.md5Hex(password);
        String pair = username + ":" + md5Pwd;
        return pair;
    }
    private static String getMassJsonContent() {
        JSONObject messageData = new JSONObject( );
        List<Object> items = new ArrayList<>( );
        JSONObject data = new JSONObject( );
        data.put("to","15094305633");
        items.add(data);
        messageData.put("batchName","测试系统接入群发测试");
        messageData.put("items",items);
        messageData.put("content","测试系统接入测试短信");
        messageData.put("msgType","测试系统接入群发测试");
        messageData.put("batchName","sms");
        messageData.put("bizType","100");
        return messageData.toJSONString();
    }

    public static void main(String[] args) {
        String URL = "http://192.168.1.102:9090/com.cese2.sso.apps.all.login";
        JSONObject param = new JSONObject(  );
        param.put("empCode","1003918");
        String result = sendPostHttpRequest(URL,param);
        System.out.println(result);
    }
}
